import _ from "lodash";
import { basic } from "../../api";
import { Storage } from "../../libs/storage";

const LOCAL = new (class {
  constructor() {
    this.$storage = new Storage("DICTIONARY", localStorage);
  }
  get length () {
    if (!this._dictionaries) {
      return 0;
    }
    return Object.keys(this._dictionaries).length;
  }
  get dictionaries () {
    this._dictionaries = this.$storage.read("dictionaries");
    return this._dictionaries;
  }
  set dictionaries (dictionaries) {
    this.$storage.write("dictionaries", dictionaries, 10 * 60);
  }
})();

const MUTATION_TYPES = {
  DICTIONARIES: "DICTIONARIES",
  RESOURCES: "RESOURCES",
  SHIPPER: "SHIPPER",
  CARRIER: "CARRIER"
};

const state = {
  dictionaries: {},
  resources: [],
  shipper: [],
  carrier: []
};
const getters = {};

const mutations = {
  [MUTATION_TYPES.DICTIONARIES] (state, dictionaries) {
    state.dictionaries = dictionaries;
  },
  [MUTATION_TYPES.RESOURCES] (state, resources) {
    state.resources = resources;
  },
  [MUTATION_TYPES.SHIPPER] (state, shipper) {
    state.shipper = shipper;
  },
  [MUTATION_TYPES.CARRIER] (state, carrier) {
    state.carrier = carrier;
  }
};

const actions = {
  async loadDictionaries ({ commit }) {
    if (LOCAL.dictionaries && LOCAL.length > 0) {
      commit(MUTATION_TYPES.DICTIONARIES, LOCAL.dictionaries);
      return LOCAL.dictionaries;
    }

    let response = await basic.loadDictionaries({ size: 500 });
    if (response.code === 0) {
      let dictionaries = _.groupBy(response.data.records, "name");
      commit(MUTATION_TYPES.DICTIONARIES, dictionaries);
      LOCAL.dictionaries = dictionaries;
      return dictionaries;
    }
  },
  async loadResources ({ commit }) {
    let response = await basic.loadResources({ size: 500 });
    if (response.code === 0) {
      let resources = response.data.records;
      commit(MUTATION_TYPES.RESOURCES, resources);
      return resources;
    }
  },
  async loadShipper ({ commit }) {
    let response = await basic.loadCustomers({ size: 500, status: 1 });
    if (response.code === 0) {
      let resources = response.data.records;
      commit(MUTATION_TYPES.SHIPPER, resources);
      return resources;
    }
  },
  async loadCarrier ({ commit }) {
    let response = await basic.loadCarriers({ size: 500, status: [1, 3] });
    if (response.code === 0) {
      let resources = response.data.records;
      commit(MUTATION_TYPES.CARRIER, resources);
      return resources;
    }
  }
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
  MUTATION_TYPES
};
